package com.woniu.auth.service.Imp;


import com.woniu.auth.Vo.LoginVo;
import com.woniu.auth.feign.UserFeign;
import com.woniu.auth.service.LoginService;
import com.woniu.common.constant.Constants;
import com.woniu.common.core.redis.RedisCache;
import com.woniu.common.enums.ExceptionCode;
import com.woniu.common.exception.CustomException;
import com.woniu.common.utils.StringUtils;


import com.woniu.common.utils.sign.Md5Utils;
import com.woniu.common.utils.token.JwtTokenUtils;
import com.woniu.user.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
@Service
public class LoginServiceImp implements LoginService {

    @Autowired
    private RedisCache redisCache;

    @Resource
    private UserFeign userFeign;
    @Override
    public String login(LoginVo loginVo) {
        String verifyCode = redisCache.getCacheObject(Constants.CAPTCHA_CODE_KEY + loginVo.getUuid());
        if(!StringUtils.equals(verifyCode,loginVo.getCode())){
            throw  new CustomException(ExceptionCode.INVALID_KAPTCHA);
        }

        User user = new User();
        user.setUserName(loginVo.getUsername());
        user.setUserPassword(loginVo.getPassword());
        User user1 = userFeign.getUser(user.getUserName(),user.getUserPassword());
        if(ObjectUtils.isEmpty(user1)){
            throw new CustomException(ExceptionCode.INVALID_USERNAME_PASSWORD);
        }
        String jwt = JwtTokenUtils.generateJwtToken(user1.getUserId(),user1.getUserName(),user1.getUserAccount());
        return jwt;
    }

    @Override
    public String weblogin(LoginVo loginVo) {
        String verifyCode = redisCache.getCacheObject(Constants.CAPTCHA_CODE_KEY + loginVo.getUuid());
        if(!StringUtils.equals(verifyCode,loginVo.getCode())){
            throw  new CustomException(ExceptionCode.INVALID_KAPTCHA);
        }

        System.out.println(loginVo);
        User user = new User();
        user.setUserName(loginVo.getUsername());
        user.setUserPassword(loginVo.getPassword());
        user.setUserPassword(Md5Utils.hash(Md5Utils.hash(user.getUserPassword())));
        User user1 = userFeign.getUser2(user.getUserName(),user.getUserPassword());
        if(ObjectUtils.isEmpty(user1)){
            throw new CustomException(ExceptionCode.INVALID_USERNAME_PASSWORD);
        }
        String jwt = JwtTokenUtils.generateWebJwtToken(user1.getUserId(),user1.getUserName(),user1.getUserAccount());
        System.out.println("我允许了");
        return jwt;
    }
}
